<template>
  <div class="vc-page vc-page-safe">
    <div>
      <div v-for="item in items" :key="item.key">
        <span>{{ item.label }}：</span>
        <el-input
          v-model="data[item.code]"
          :maxlength="item.maxlength"
          placeholder="请输入"
          size="small"
          @input="item.input"
          @change="item.change">
          <template v-if="item.slot" slot="append">{{ item.slot }}</template>
        </el-input>
      </div>

      <div>
        <span>密码复杂度：</span>
        <div>
          <el-checkbox
            v-model="rule.value"
            v-for="(rule, idx) in pwdRules"
            :key="idx"
            @change="changePwdRules(idx, $event)">{{ rule.label }}</el-checkbox>
        </div>
      </div>

      <div>
        <span>可登录时间段：</span>
        <el-time-picker
          is-range
          editable
          size="small"
          format="HH:mm"
          value-format="timestamp"
          v-model="whiteTimes"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :clearable="false"
          @change="changeWhiteTime">
        </el-time-picker>
      </div>

      <div>
        <span>可登录IP网段：</span>
        <ip-segment
          :ips="data.WHITE_IP"
          code="WHITE_IP"
          @modify="modify">
        </ip-segment>
      </div>
    </div>
  </div>
</template>

<script>
import IpSegment from './ip-segment'

export default {
  name: 'safe',
  components: { IpSegment },
  data () {
    const dayStart = +new Date().floor()
    return {
      allData: [],
      data: {
        NUM_FOR_MAX_SESSION_COUNT: '',
        SESSION_TIMEOUT: '',
        CYCLE_AUTO_SLEEP: '',
        CIPHER_TIMEOUT: '',
        DAY_FOR_ERROR_LOGIN_NUM: '',
        PWD_CHECK_RULES: '',
        WHITE_TIME_PERIOD: '',
        WHITE_IP: ''
      },
      pwdRules: [
        { label: '数字', value: false },
        { label: '大写字母', value: false },
        { label: '小写字母', value: false },
        { label: '特殊字符', value: false }
      ],
      whiteTimes: [dayStart, dayStart],
      dayStart: dayStart,
      items: [
        {
          label: '最大并发会话连接数',
          code: 'NUM_FOR_MAX_SESSION_COUNT',
          maxLength: 10,
          input: value => {
            value = value.replace(/[^\d]/g, '')
            this.data['NUM_FOR_MAX_SESSION_COUNT'] = value * 1 === 0 ? '1' : `${value * 1}`
          },
          change: value => {
            this.modify('NUM_FOR_MAX_SESSION_COUNT', value)
          }
        },
        {
          label: '会话终止时长',
          code: 'SESSION_TIMEOUT',
          maxLength: 2,
          input: value => {
            value = value.replace(/[^\d]/g, '')
            value = value * 1 === 0 ? '1' : `${value * 1}`
            value * 1 > 30 && (value = '30')
            this.data['SESSION_TIMEOUT'] = value
          },
          change: value => {
            this.modify('SESSION_TIMEOUT', value * 60 * 1000)
          },
          slot: '分钟'
        },
        {
          label: '账号自动休眠扫描周期',
          code: 'CYCLE_AUTO_SLEEP',
          maxLength: 10,
          input: value => {
            value = value.replace(/[^\d]/g, '')
            this.data['CYCLE_AUTO_SLEEP'] = value * 1 === 0 ? '1' : `${value * 1}`
          },
          change: value => {
            this.modify('CYCLE_AUTO_SLEEP', value * 60 * 1000)
          },
          slot: '分钟'
        },
        {
          label: '强制用户定期修改密码周期',
          code: 'CIPHER_TIMEOUT',
          maxLength: 2,
          input: value => {
            value = value.replace(/[^\d]/g, '')
            value = value * 1 === 0 ? '1' : `${value * 1}`
            value * 1 > 90 && (value = '90')
            this.data['CIPHER_TIMEOUT'] = value
          },
          change: value => {
            this.modify('CIPHER_TIMEOUT', value * 24 * 60 * 60 * 1000)
          },
          slot: '天'
        },
        {
          label: '连续登录失败锁定次数限制',
          code: 'DAY_FOR_ERROR_LOGIN_NUM',
          maxLength: 2,
          input: value => {
            value = value.replace(/[^\d]/g, '')
            value = value * 1 === 0 ? '1' : `${value * 1}`
            value * 1 > 10 && (value = '10')
            this.data['DAY_FOR_ERROR_LOGIN_NUM'] = value
          },
          change: value => {
            this.modify('DAY_FOR_ERROR_LOGIN_NUM', value)
          },
          slot: '次'
        }
      ]
    }
  },
  created () {
    this.findAllSafeConfig()
  },
  methods: {
    /**
     * 查询所有安全配置
     */
    findAllSafeConfig () {
      this.$api.findAllSafeConfig().then(res => {
        if (!res.success || !res.data) {
          return
        }
        for (let data of res.data) {
          this.allData[data.code] = data
          let times
          if (['SESSION_TIMEOUT', 'CYCLE_AUTO_SLEEP'].includes(data.code)) {
            times = 60 * 1000
          }
          if (data.code === 'CIPHER_TIMEOUT') {
            times = 24 * 60 * 60 * 1000
          }
          this.data[data.code] = times ? `${Math.floor(data.val / times)}` : data.val
        }
        this.pwdRules.forEach((item, idx) => {
          item.value = this.data['PWD_CHECK_RULES'].charAt(idx) === '1'
        })
        let arr = JSON.parse(this.data['WHITE_TIME_PERIOD']).map(item => item >= 86400000 ? item - 86400000 : item)
        this.whiteTimes = [this.dayStart + arr[0], this.dayStart + arr[0] + arr[1]]
      })
    },
    /**
     * 修改安全配置
     */
    modify (code, val) {
      this.$api.modifySafeConfig({
        data: Object.assign({}, this.allData[code], { val: typeof val === 'object' ? JSON.stringify(val) : val })
      }).then(res => {
        this.findAllSafeConfig()
        res.success && this.$notifyBox('保存成功', 'success', 1000)
      })
    },
    /**
     * '密码校验规则'改变事件
     */
    changePwdRules (idx, value) {
      let rules = this.pwdRules.map(item => { return item.value ? '1' : '0' })
      this.modify('PWD_CHECK_RULES', rules.join(''))
    },
    /**
     * '登录时间段'改变事件
     */
    changeWhiteTime (value) {
      let end = value[1] - value[0]
      let start = value[0] - this.dayStart
      this.modify('WHITE_TIME_PERIOD', [start, end + (start === 0 && end === 0 ? 86400000 : 0)])
    }
  }
}
</script>

<style lang="less">
.vc-page-safe {
  height: calc(100% - 30px);
  & > div {
    width: calc(100% - 30px);
    min-height: calc(100% - 60px);
    text-align: left;
    background: #fff;
    padding: 30px 15px;
    margin-bottom: 15px;
    & > div {
      display: flex !important;
      margin-bottom: 15px;
      & > span {
        display: inline-block;
        width: 200px;
        text-align: right;
        height: 30px;
        line-height: 30px;
        margin-right: 10px;
        color: #818181;
      }
      .el-checkbox {
        display: block;
        line-height: 30px;
      }
      & > .el-input, & > .el-date-editor {
        width: 240px !important;
      }
    }
  }
}
</style>
